package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class HttpServeletRequest {
    private Socket socket;
    private String method;
    private String uri;
    private String vp;

    private String requestURI;
    private String queryString;
    Map<String,String> parameters = new HashMap<>();

    Map<String,String> hreders;

    public HttpServeletRequest(Socket socket) throws IOException, EmptyRequestException {
        this.socket = socket;
        parseRequestLine();
        headRequestLine();
        parseContent();


    }
    public void parseRequestLine() throws IOException, EmptyRequestException {
        String line = readLine();
        if (line.isEmpty()){
            throw new EmptyRequestException();
        }
        System.out.println("请求头："+line);
        String[] str = line.split("\\s");
        method = str[0];
        uri = str[1];
        vp = str[2];
        parseURI();
    }
    public void parseURI(){
        String[] str = uri.split("\\?");
        requestURI = str[0];
        if (str.length>1){
            queryString = str[1];
            parseParameter(queryString);
        }
        System.out.println("表单数据"+parameters);
    }
    public void parseParameter(String line){
        try {

            line= URLDecoder.decode(line,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String[] data = line.split("&");
        for (String para : data){
            data =para.split("=",2);
            parameters.put(data[0],data[1]);
//                data = para.split("=");
//                parameter.put(data[0],data.length>1?data[1]:"" );
        }
    }
    public void headRequestLine() throws IOException {
        hreders = new HashMap<>();
        while (true){
            String line = readLine();
            if (line.isEmpty()){
                break;
            }
            String[] str = line.split(":\\s");
            hreders.put(str[0].toLowerCase(Locale.ROOT),str[1]);
        }
        System.out.println(hreders);
    }
    public void parseContent() throws IOException {
        String contentLength = getHreder("content-length");
        if (contentLength!=null){
            int length = Integer.parseInt(contentLength);
            byte[] data = new byte[length];
            InputStream in = socket.getInputStream();
            in.read(data);
            String contentType = getHreder("content-type");
            if ("application/x-www-form-urlencoded".equals(contentType)){
                String line = new String(data,StandardCharsets.ISO_8859_1);
                line = URLDecoder.decode(line,"UTF-8");
                System.out.println(line);
                parseParameter(line);
            }
//            else if (){
//
//            }

        }

    }

    private String readLine() throws IOException {
        StringBuilder builder = null;
        InputStream in = socket.getInputStream();
        int d;
        char cur = 'a' , pre='a';
        builder = new StringBuilder();
        while ((d=in.read())!=-1){
            cur = (char) d;
            if (cur==10 && pre ==13){
                break;
            }
            builder.append(cur);
            pre = cur;

            }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getVp() {
        return vp;
    }

    public String getHreder(String name) {
        name = name.toLowerCase(Locale.ROOT);
        return hreders.get(name);
    }

    public String getRequestURI() {
        return requestURI;
    }

    public String getQueryString() {
        return queryString;
    }

    public String getParameter(String name) {
        return parameters.get(name);
    }
}
